package com.zsk.service.impl;

import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import com.zsk.bean.TableParams;
import com.zsk.service.IMvnPrjGenService;
import com.zsk.util.FileUtil;
import com.zsk.util.MvnPrjUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class MvnPrjGenServiceImpl implements IMvnPrjGenService {

	@Override
	public boolean genMvnPrjCode(List<TableParams> list, String packageName, String groupId, String artifactId) {
		genCommonCode(packageName,artifactId);
		genPomXml(packageName,artifactId);
		return true;
	}

	
	protected void genCommonCode(String packageName,String artifactId) {
		String dir =MvnPrjUtil.getWorkCodeDir(artifactId,packageName);
		String beanDir = dir + "/bean";
		String utilDir = dir + "/util";

		String pageStr = FileUtil.readTxtFile("template/PageBean.java").toString();
		String resStr = FileUtil.readTxtFile("template/ResultBean.java").toString();
		String jpaUtilStr = FileUtil.readTxtFile("template/JPAUtil.java").toString();

		pageStr = pageStr.replace("#1", packageName + ".bean");
		resStr = resStr.replace("#1", packageName + ".bean");
		jpaUtilStr = jpaUtilStr.replace("#1", packageName + ".util").replace("#2", packageName + "bean.PageBean;");

		FileUtil.makeDir(beanDir);
		FileUtil.makeDir(utilDir);
		FileUtil.writeTxtFile(pageStr, beanDir + "/PageBean.java");
		FileUtil.writeTxtFile(resStr, beanDir + "/ResultBean.java");
		FileUtil.writeTxtFile(jpaUtilStr, dir + "/util/JPAUtil.java");
	}

	protected  void genPomXml(String groupId,String artifactId) {
		String dir = MvnPrjUtil.workingDir+"/"+artifactId;
		String pom = FileUtil.readTxtFile("template/pom.xml").toString();
		pom = pom.replace("#1", groupId)
		         .replace("#2", artifactId);
		FileUtil.writeTxtFile(pom, dir + "/pom.xml");
		try {
			String resDir=dir+"/src/main/resources";
			FileUtil.emptyDir(resDir);
			FileCopyUtils.copy(FileUtils.getFile("template/application.yml"), FileUtils.getFile(resDir+"/application.yml"));
		} catch (IOException e) {
			log.error(e.toString());
		}
	}
}
